package com.baizhi.service.ServiceImpl;

import com.baizhi.annotation.LogAnnotation;
import com.baizhi.service.UserService;
import com.baizhi.service.UserThreadService;
import com.baizhi.util.ThreadPollUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * Created by Administrator on 2019/4/6.
 */
@Service
public class UserThreadServiceImpl implements UserThreadService {
    @Autowired
    UserService userService;


    /**
     * 没有优化五万条数据用时9710ms;
     * @return
     */
    @Override
    @LogAnnotation("查询注册量")
    public Map selectAllCount1() {
        Map map = new HashMap<>();
//        注册量
        Map map1 = userService.selectDayCount();
//        地区分布
        List<Map> map2 = userService.selectAddressCount();
//        男女比例
        Map map3 = userService.selectSexCount();

        map.put("time",map1);
        map.put("address",map2);
        map.put("sex",map3);
        return map;
    }


    /**
     * 通过创建多个线程进行优化
     * 五万条数据用时7867ms
     * @return
     */
    @Override
    @LogAnnotation("进行线程优化")
    public Map selectAllCount2() throws InterruptedException {
        Map map=new HashMap();

        //创建计数器  计数为3
        CountDownLatch countDownLatch=new CountDownLatch(3);
        /*开启三个线程*/
        ThreadPollUtil.executor.execute(new Runnable() {
            @Override
            public void run() {
                Map map1 = userService.selectDayCount();
                map.put("time",map1);
                try {
                    countDownLatch.countDown();
                } catch (Exception e) {
                    countDownLatch.countDown();
                    e.printStackTrace();
                }
            }
        });
        ThreadPollUtil.executor.execute(new Runnable() {
            @Override
            public void run() {
                List<Map> map2 = userService.selectAddressCount();
                map.put("address",map2);
                try {
                    countDownLatch.countDown();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
        ThreadPollUtil.executor.execute(new Runnable() {
            @Override
            public void run() {
                Map map3 = userService.selectSexCount();
                map.put("sex",map3);

                try {
                    countDownLatch.countDown();
                } catch (Exception e) {
                    countDownLatch.countDown();
                }
            }
        });

        /*3.使用await()方法 让主线程等待任务线程执行结束*/
        countDownLatch.await();
        return map;
    }
}
